const { ccclass, property } = cc._decorator;

enum Time {
    none = 0,
    onLoad = 1,
    start = 2,
    onEnable = 3,
    onDisable = 4,
    onDestroy = 5
}

@ccclass
export default class ToggleGroup extends cc.Component {
    @property
    protected _time: Time = Time.onLoad;
    @property({
        type: cc.Enum(Time),
        tooltip: '触发的时机'
    })
    get time() { return this._time; }
    set time(value) {
        this._time = value;
        if (this._time === Time.none) {
            this.selectIndex = -1;
        }
    }

    @property
    protected _selectIndex: number = 0;
    @property
    get selectIndex() { return this._selectIndex; }
    set selectIndex(value) {
        this._selectIndex = value;
        this._toggleClickByIndex(this._selectIndex);
    }

    @property({
        tooltip: '是否允许重复点击'
    })
    allwaysClick: boolean = false;

    // 开始时的下标
    private _startIndex = 0;
    // 当前toggle
    private _currToggle = null;

    private _toggles = [];
    private get toggles() {
        return this._updateToggles();
    }

    onLoad() {
        this._startIndex = this.selectIndex;

        if (this.time === Time.onLoad) this._toggleInit();
    }

    start() { if (this.time === Time.start) this._toggleInit(); }
    onEnable() { if (this.time === Time.onEnable) this._toggleInit(); }
    onDisable() { if (this.time === Time.onDisable) this._toggleInit(); }
    onDestroy() { if (this.time === Time.onDestroy) this._toggleInit(); }

    private _updateToggles() {
        this._toggles = this.node.getComponentsInChildren('toggle') || [];
        return this._toggles;
    }

    private _toggleInit() {
        this.selectIndex = this._startIndex || 0;
    }

    private _toggleClickByToggle(toggle) {
        // 检测是否不允许重复点击
        if (!this.allwaysClick && this._currToggle === toggle) {
            return;
        }
        this._selectIndex = this.toggles.indexOf(toggle);
        this._toggleClick(toggle);
    }

    private _toggleClickByIndex(index) {
        const toggle = this.toggles[index];
        if (toggle) {
            this._toggleClick(toggle);
        } else {
            console.error(`没找到下标为${index}的toggle`);
        }
    }

    private _toggleClick(toggle) {
        if (!toggle) {
            return;
        }

        let old = null;

        if (this._currToggle !== toggle) {
            old = this._currToggle;
            this._currToggle = toggle;

            old && old.cancel();
        }

        this._currToggle && this._currToggle.select();

        this.node.emit('toggleClick', { select: toggle, cancel: old, index: this.selectIndex });
    }
}
